using Microsoft.Win32;
using Toolbox.Forms;

namespace Toolbox.Model.Settings
{
    public class SettingsPage : BaseTabPage, IDisposable
    {
        /// <summary>
        /// 页签名称
        /// </summary>
        public override string TabName => "设置";

        /// <summary>
        /// 配置文件名称（不含路径和扩展名）
        /// </summary>
        public override string ConfigFileName => "Settings";

        /// <summary>
        /// 页签序号（用于排序）
        /// </summary>
        public override int TabOrder => 99;

        // 保存页签管理组的引用，用于调整高度
        private GroupBox? _tabManagementGroup;

        // 保存系统设置组的引用，用于调整位置
        private GroupBox? _systemSettingsGroup;

        // 保存信息标签的引用，用于调整位置
        private Label? _infoLabel;

        // 保存开机启动复选框的引用
        private CheckBox? _startupCheckbox;

        // 初始化系统设置页面 (非静态实现)
        public override void InitializePage(TabPage tabPage, MainForm mainForm)
        {
            // 从配置文件加载关闭窗口行为设置
            int closeWindowAction = ConfigManager.Instance.GetIntSetting("system.closeWindowAction", 0);
            mainForm.CloseWindowAction = (MainForm.CloseWindowActionEnum)closeWindowAction;

            // 主面板
            Panel mainPanel = new() { Dock = DockStyle.Fill, Padding = new Padding(20) };
            tabPage.Controls.Add(mainPanel);

            // 标题
            Label titleLabel = new()
            {
                Text = "系统设置",
                Font = new Font("Microsoft YaHei", 16, FontStyle.Bold),
                Location = new Point(10, 10),
                AutoSize = true
            };
            mainPanel.Controls.Add(titleLabel);

            // 设置组
            GroupBox settingsGroup = new()
            {
                Text = "窗口设置",
                Location = new Point(10, 50),
                Size = new Size(530, 80)
            };
            mainPanel.Controls.Add(settingsGroup);

            // 关闭窗口行为设置
            Label closeWindowLabel = new()
            {
                Text = "关闭窗口时: ",
                Location = new Point(30, 40),
                Size = new Size(100, 20),
                TextAlign = ContentAlignment.MiddleRight
            };
            settingsGroup.Controls.Add(closeWindowLabel);

            // 水平排列的RadioButton组
            Panel closeWindowGroup = new()
            {
                Location = new Point(140, 35),
                Size = new Size(380, 30)
            };
            settingsGroup.Controls.Add(closeWindowGroup);

            RadioButton askEveryTimeRadio = new()
            {
                Text = "每次询问",
                Location = new Point(10, 5),
                Checked = mainForm.CloseWindowAction == MainForm.CloseWindowActionEnum.AskEveryTime,
                Tag = MainForm.CloseWindowActionEnum.AskEveryTime
            };
            askEveryTimeRadio.CheckedChanged += (s, e) =>
            {
                if (askEveryTimeRadio.Checked)
                {
                    mainForm.CloseWindowAction = MainForm.CloseWindowActionEnum.AskEveryTime;
                    ConfigManager.Instance.SaveIntSetting("system.closeWindowAction", (int)MainForm.CloseWindowActionEnum.AskEveryTime);
                }
            };
            closeWindowGroup.Controls.Add(askEveryTimeRadio);

            RadioButton minimizeToTrayRadio = new()
            {
                Text = "系统托盘",
                Location = new Point(120, 5),
                Checked = mainForm.CloseWindowAction == MainForm.CloseWindowActionEnum.MinimizeToTray,
                Tag = MainForm.CloseWindowActionEnum.MinimizeToTray
            };
            minimizeToTrayRadio.CheckedChanged += (s, e) =>
            {
                if (minimizeToTrayRadio.Checked)
                {
                    mainForm.CloseWindowAction = MainForm.CloseWindowActionEnum.MinimizeToTray;
                    ConfigManager.Instance.SaveIntSetting("system.closeWindowAction", (int)MainForm.CloseWindowActionEnum.MinimizeToTray);
                }
            };
            closeWindowGroup.Controls.Add(minimizeToTrayRadio);

            RadioButton exitProgramRadio = new()
            {
                Text = "退出程序",
                Location = new Point(230, 5),
                Checked = mainForm.CloseWindowAction == MainForm.CloseWindowActionEnum.ExitProgram,
                Tag = MainForm.CloseWindowActionEnum.ExitProgram
            };
            exitProgramRadio.CheckedChanged += (s, e) =>
            {
                if (exitProgramRadio.Checked)
                {
                    mainForm.CloseWindowAction = MainForm.CloseWindowActionEnum.ExitProgram;
                    ConfigManager.Instance.SaveIntSetting("system.closeWindowAction", (int)MainForm.CloseWindowActionEnum.ExitProgram);
                }
            };
            closeWindowGroup.Controls.Add(exitProgramRadio);

            // 页签管理设置组
            GroupBox tabManagementGroup = new()
            {
                Text = "页签管理",
                Location = new Point(10, 140),
                Size = new Size(530, 50)  // 设置更小的初始高度，将在UpdateTabManagementGroupHeight中调整
            };
            mainPanel.Controls.Add(tabManagementGroup);

            // 保存页签管理组的引用
            _tabManagementGroup = tabManagementGroup;

            // 获取所有已注册的页签
            List<BaseTabPage> allTabs = TabRegistry.GetAllTabs();
            List<string> enabledTabs = TabRegistry.GetEnabledTabNames();

            // 创建页签块状控件
            CreateTabBlocks(allTabs, enabledTabs, mainForm);

            // 开机启动设置组
            GroupBox startupGroup = new()
            {
                Text = "系统设置",
                Location = new Point(10, 270),
                Size = new Size(530, 60)
            };
            mainPanel.Controls.Add(startupGroup);

            // 保存系统设置组的引用
            _systemSettingsGroup = startupGroup;

            // 开机启动复选框
            CheckBox startupCheckbox = new()
            {
                Text = "开机自动启动",
                Location = new Point(30, 25),
                Size = new Size(150, 20),
                Checked = IsStartupEnabled()
            };
            startupCheckbox.CheckedChanged += (s, e) =>
            {
                SetStartupEnabled(startupCheckbox.Checked);
                ConfigManager.Instance.SaveBoolSetting("system.autoStart", startupCheckbox.Checked);
            };
            startupGroup.Controls.Add(startupCheckbox);

            // 同步开机启动状态
            SyncStartupStatus(mainForm, startupCheckbox);

            // 其他设置说明
            Label infoLabel = new()
            {
                Text = "提示：\r\n1. 修改设置后将自动保存到配置文件\r\n2. 所有设置将在下次程序启动时生效\r\n3. 鼠标悬浮到窗口底部可调整窗口高度\r\n4. 页签管理中的更改将立即生效\r\n5. 可以通过拖拽页签标题来调整页签顺序",
                Location = new Point(40, 340),
                Size = new Size(480, 85),
                AutoSize = false,
                TextAlign = ContentAlignment.TopLeft,
                ForeColor = Color.Gray
            };
            mainPanel.Controls.Add(infoLabel);

            // 保存信息标签的引用
            _infoLabel = infoLabel;

            // 添加窗口大小改变事件处理，以便调整控件宽度
            tabPage.Resize += (s, e) =>
            {
                // 计算新的控件宽度，统一使用20像素的左右边距
                int newWidth = mainPanel.Width - 20; // 减去左右边距

                // 调整设置组的宽度
                settingsGroup.Width = newWidth;

                // 调整RadioButton组的宽度
                closeWindowGroup.Width = newWidth - 150; // 减去标签和左边距

                // 页签管理设置组的宽度
                tabManagementGroup.Width = newWidth;

                // 重新排列页签块
                RearrangeTabBlocks();

                // 调整开机启动设置组的宽度
                startupGroup.Width = newWidth;

                // 调整其他设置说明标签的宽度
                infoLabel.Width = newWidth - 80; // 减去左右边距
            };

            // 保存开机启动复选框的引用，以便后续同步状态
            _startupCheckbox = startupCheckbox;
        }

        /// <summary>
        /// 作者：huobing
        /// 功能：创建页签块状控件
        /// </summary>
        /// <param name="allTabs">所有页签</param>
        /// <param name="enabledTabs">已启用的页签名称</param>
        /// <param name="mainForm">主窗口引用</param>
        private void CreateTabBlocks(List<BaseTabPage> allTabs, List<string> enabledTabs, MainForm mainForm)
        {
            if (_tabManagementGroup == null)
            {
                return;
            }

            // 清除现有控件（只清除按钮控件，保留其他控件）
            var buttonsToRemove = _tabManagementGroup.Controls.OfType<Button>().ToList();
            foreach (var button in buttonsToRemove)
            {
                _tabManagementGroup.Controls.Remove(button);
            }

            // 块的宽度和高度
            int blockWidth = 70; // 减小块宽度
            int blockHeight = 25; // 减小块高度
            int blockSpacing = 12; // 减小间距

            // 计算每行可容纳的块数
            int blocksPerRow = Math.Max(1, ((_tabManagementGroup.Width - 40) + blockSpacing) / (blockWidth + blockSpacing)); // 减去左右边距

            // 当前位置
            int currentX = 20; // 左边距
            int currentY = 30; // 标题栏下方
            int blocksInCurrentRow = 0;

            // 为每个页签创建块
            foreach (BaseTabPage tab in allTabs)
            {
                // 跳过设置页签本身，不允许禁用
                if (tab.TabName == "设置")
                {
                    continue;
                }

                // 创建块状按钮
                Button tabBlock = new()
                {
                    Text = tab.TabName,
                    Location = new Point(currentX, currentY),
                    Size = new Size(blockWidth, blockHeight),
                    TextAlign = ContentAlignment.MiddleCenter,
                    UseVisualStyleBackColor = true,
                    // 设置块的外观
                    FlatStyle = FlatStyle.Flat
                };
                tabBlock.FlatAppearance.BorderSize = 1;

                // 根据启用状态设置颜色
                if (enabledTabs.Contains(tab.TabName))
                {
                    tabBlock.BackColor = Color.LightGreen;
                    tabBlock.FlatAppearance.BorderColor = Color.Green;
                }
                else
                {
                    tabBlock.BackColor = Color.LightGray;
                    tabBlock.FlatAppearance.BorderColor = Color.DarkGray;
                }

                // 添加点击事件处理
                tabBlock.Click += (s, e) =>
                {
                    // 切换启用状态
                    bool newState = !enabledTabs.Contains(tab.TabName);
                    // 通知主窗口更新页签
                    var mainTabControl = mainForm.Controls.Find("mainTabControl", true).FirstOrDefault() as CustomTabControl;
                    if (mainTabControl != null)
                    {
                        if (newState)
                        {
                            // 启用页签
                            TabRegistry.SetTabEnabled(tab.TabName, true);
                            enabledTabs.Add(tab.TabName);
                            tabBlock.BackColor = Color.LightGreen;
                            tabBlock.FlatAppearance.BorderColor = Color.Green;
                            mainTabControl.AddTab(tab.TabName);
                        }
                        else
                        {
                            // 禁用页签
                            TabRegistry.SetTabEnabled(tab.TabName, false);
                            enabledTabs.Remove(tab.TabName);
                            tabBlock.BackColor = Color.LightGray;
                            tabBlock.FlatAppearance.BorderColor = Color.DarkGray;
                            mainTabControl.RemoveTab(tab.TabName);
                        }
                        // 保存配置
                        TabRegistry.SaveTabStatuses();
                    }
                };

                // 添加到页签管理组
                _tabManagementGroup.Controls.Add(tabBlock);

                // 更新位置
                currentX += blockWidth + blockSpacing;
                blocksInCurrentRow++;

                // 检查是否需要换行
                if (blocksInCurrentRow >= blocksPerRow)
                {
                    currentX = 20; // 重置到左边距
                    currentY += blockHeight + blockSpacing;
                    blocksInCurrentRow = 0;
                }
            }

            // 更新页签管理组的高度
            UpdateTabManagementGroupHeight();
        }

        /// <summary>
        /// 作者：huobing
        /// 功能：重新排列页签块
        /// </summary>
        private void RearrangeTabBlocks()
        {
            if (_tabManagementGroup == null)
            {
                return;
            }

            // 块的宽度和高度（与CreateTabBlocks中保持一致）
            int blockWidth = 70; // 减小块宽度
            int blockHeight = 25; // 减小块高度
            int blockSpacing = 12; // 减小间距

            // 计算每行可容纳的块数
            int blocksPerRow = Math.Max(1, ((_tabManagementGroup.Width - 40) + blockSpacing) / (blockWidth + blockSpacing)); // 减去左右边距

            // 当前位置
            int currentX = 20; // 左边距
            int currentY = 30; // 标题栏下方
            int blocksInCurrentRow = 0;

            // 重新排列所有块
            foreach (Control control in _tabManagementGroup.Controls.OfType<Button>())
            {
                control.Location = new Point(currentX, currentY);
                control.Size = new Size(blockWidth, blockHeight);

                // 更新位置
                currentX += blockWidth + blockSpacing;
                blocksInCurrentRow++;

                // 检查是否需要换行
                if (blocksInCurrentRow >= blocksPerRow)
                {
                    currentX = 20; // 重置到左边距
                    currentY += blockHeight + blockSpacing;
                    blocksInCurrentRow = 0;
                }
            }

            // 更新页签管理组的高度
            UpdateTabManagementGroupHeight();
        }

        /// <summary>
        /// 作者：huobing
        /// 功能：窗口大小改变事件处理
        /// </summary>
        private void SettingsPage_Resize(object? sender, EventArgs e)
        {
            // 重新排列页签块
            RearrangeTabBlocks();

            // 获取TabPage的宽度
            if (sender is not TabPage tabPage)
            {
                return;
            }

            // 调整系统设置组的宽度
            if (_systemSettingsGroup != null)
            {
                _systemSettingsGroup.Width = tabPage.Width - 40;
            }

            // 调整提示标签的位置和宽度
            if (_infoLabel != null && _systemSettingsGroup != null)
            {
                _infoLabel.Top = _systemSettingsGroup.Bottom + 20;
                _infoLabel.Width = tabPage.Width - 40;
            }
        }

        /// <summary>
        /// 作者：huobing
        /// 功能：更新页签管理组的高度
        /// </summary>
        private void UpdateTabManagementGroupHeight()
        {
            if (_tabManagementGroup == null)
            {
                return;
            }

            // 块的宽度和高度（与CreateTabBlocks中保持一致）
            int blockWidth = 70; // 减小块宽度
            int blockHeight = 25; // 减小块高度
            int blockSpacing = 12; // 减小间距

            // 计算每行可容纳的块数
            int blocksPerRow = Math.Max(1, ((_tabManagementGroup.Width - 40) + blockSpacing) / (blockWidth + blockSpacing)); // 减去左右边距

            // 获取所有页签按钮（不包括设置页签）
            var tabButtons = _tabManagementGroup.Controls.OfType<Button>().ToList();
            int tabCount = tabButtons.Count;

            // 如果没有页签按钮，使用最小高度
            if (tabCount == 0)
            {
                _tabManagementGroup.Height = 50; // 减小最小高度
                return;
            }

            // 计算需要的行数
            int rowsNeeded = (int)Math.Ceiling((double)tabCount / blocksPerRow);

            // 计算内容所需高度
            int contentRequiredHeight = rowsNeeded * (blockHeight + blockSpacing);
            if (rowsNeeded > 0)
            {
                contentRequiredHeight -= blockSpacing; // 最后一行不需要额外的间距
            }

            // 计算页签管理组的总高度（标题栏高度 + 内容高度 + 底部边距）
            int titleBarHeight = 20; // 减小标题栏高度
            int topMargin = 25; // 减小内容顶部边距
            int bottomMargin = 5; // 减小底部边距
            int requiredHeight = titleBarHeight + topMargin + contentRequiredHeight + bottomMargin;

            // 设置页签管理组的高度，但确保最小高度
            int newHeight = Math.Max(50, requiredHeight); // 减小最小高度

            // 更新组的高度
            _tabManagementGroup.Height = newHeight;

            // 调整下方控件的位置
            int newY = _tabManagementGroup.Bottom + 15; // 减小下方控件间距
            if (_systemSettingsGroup != null)
            {
                _systemSettingsGroup.Top = newY;
                newY = _systemSettingsGroup.Bottom + 15; // 减小下方控件间距
            }

            if (_infoLabel != null)
            {
                _infoLabel.Top = newY;
            }
        }

        /// <summary>
        /// 同步开机启动状态
        /// 在切换到设置页签时调用
        /// </summary>
        /// <param name="mainForm">主窗口引用</param>
        /// <param name="startupCheckbox">开机启动复选框，如果为null则使用保存的引用</param>
        public void SyncStartupStatus(MainForm mainForm, CheckBox? startupCheckbox = null)
        {
            // 如果没有提供复选框参数，使用保存的引用
            startupCheckbox ??= _startupCheckbox;

            if (startupCheckbox == null)
            {
                return;
            }

            // 同步开机启动状态
            bool configAutoStart = ConfigManager.Instance.GetBoolSetting("system.autoStart", false);
            bool systemAutoStart = IsStartupEnabled();

            // 如果配置文件和系统状态不一致，以系统状态为准并更新配置文件
            if (configAutoStart != systemAutoStart)
            {
                ConfigManager.Instance.SaveBoolSetting("system.autoStart", systemAutoStart);
                startupCheckbox.Checked = systemAutoStart;
            }
        }

        /// <summary>
        /// 重写父类的OnTabSelected方法，在切换到设置页签时同步开机启动状态
        /// </summary>
        /// <param name="mainForm">主窗口引用</param>
        public override void OnTabSelected(MainForm mainForm)
        {
            // 调用同步开机启动状态方法
            SyncStartupStatus(mainForm);
        }

        /// <summary>
        /// 检查是否已设置开机启动
        /// </summary>
        /// <returns>如果已设置开机启动返回true，否则返回false</returns>
        public static bool IsStartupEnabled()
        {
            try
            {
                RegistryKey? key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", false);
                if (key != null)
                {
                    string? value = key.GetValue("我的工具箱") as string;
                    key.Close();
                    return !string.IsNullOrEmpty(value) && File.Exists(value);
                }
            }
            catch (Exception)
            {
                // 访问注册表失败，返回false
            }
            return false;
        }

        /// <summary>
        /// 设置开机启动
        /// </summary>
        /// <param name="enabled">是否启用开机启动</param>
        public static void SetStartupEnabled(bool enabled)
        {
            try
            {
                RegistryKey? key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                if (key != null)
                {
                    if (enabled)
                    {
                        // 设置开机启动
                        string exePath = Application.ExecutablePath;
                        key.SetValue("我的工具箱", exePath);
                    }
                    else
                    {
                        // 取消开机启动
                        key.DeleteValue("我的工具箱", false);
                    }
                    key.Close();
                }
            }
            catch (Exception)
            {
                // 访问注册表失败，忽略
            }
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }
}